
// 顶点着色器
const vs_s = `
  attribute vec4 a_Position;
  attribute float a_PointSize;
  attribute vec4 a_Color;
  varying vec4 v_Color;
  void main() {
    gl_Position = a_Position;
    gl_PointSize = a_PointSize;
    v_Color = a_Color;
  }
`;
// 片元着色器
const fs_s = `
  precision mediump float;
  varying vec4 v_Color;
  void main() {
    gl_FragColor = v_Color;
  }
`;

function main() {
  const canvas = document.getElementById('webgl');
  if (!canvas) {
    alert('Field to get canvas by id');
    return false;
  }
  const gl = canvas.getContext('webgl');
  if (!gl) {
    alert('Field to get webgl context.');
    return false;
  }
  if (!initShaders(gl, vs_s, fs_s)) {
    alert('Field to init shaders.');
    return false;
  }
  const pointCount = initVertexBuffers(gl);
  if (pointCount < 0) {
    alert('Field to init vertex buffers.');
    return false;
  }

  gl.clearColor(0, 0, 0, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.TRIANGLES, 0, pointCount);

  return true;
}

function initVertexBuffers(gl) {
  const vertices = new Float32Array([
    -0.5, +0.5, 10.0, 1.0, 0.0, 0.0, 1.0,
    +0.5, +0.5, 10.0, 0.0, 1.0, 0.0, 1.0,
    +0.0, -0.5, 10.0, 0.0, 0.0, 1.0, 1.0,
  ]);
  // 创建buffer
  const vertexBuffer = gl.createBuffer();
  if (!vertexBuffer) {
    alert('Field to vertex buffer.');
    return -1;
  }
  // 绑定buffer
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  // 向 buffer 写入数据
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

  const f_size = vertices.BYTES_PER_ELEMENT;

  const a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, f_size * 7, 0);
  gl.enableVertexAttribArray(a_Position);
  const a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
  gl.vertexAttribPointer(a_PointSize, 1, gl.FLOAT, false, f_size * 7, f_size * 2);
  gl.enableVertexAttribArray(a_PointSize);
  const a_Color = gl.getAttribLocation(gl.program, 'a_Color');
  gl.vertexAttribPointer(a_Color, 4, gl.FLOAT, false, f_size * 7, f_size * 3);
  gl.enableVertexAttribArray(a_Color);
  return Math.ceil(vertices.length / 7);
}